<?php
namespace app\Admin\controller\post;

//引入公共控制器
use app\common\controller\Backend;

use think\Request;

class Post extends Backend
{
    public function __construct(){

        //继承父类
        parent::__construct();

        $this->PostModel = Model('Post.Post');

        $this->CommentModel = Model('Post.Comment');
       
    } 

    // 首页列表
    public function index()
    {
        
        $start = $this->request->param('start', '');

        $end = $this->request->param('end', '');

        $keywords = $this->request->param('keywords', '');
     
        $where = [];

        // 开始时间
        if($start){
            $where['post.createtime'] = ['> time',$start];
        }

        // 结束时间  小于某个时间
        if($end)
        {
            $where['post.createtime'] = ['<= time',$end];
        }
        // 时间区间
        if($start && $end)
        {
            $where['post.createtime'] = ['between time',[$start, $end]];
        }
        // 关键字
        if($keywords)
        {
            $where['title'] = ['like',"%$keywords%"];
        }

        $count = $this->PostModel->count();

        // query： 分页调用的时候传参，request请求传过来的参数
        $postlist = $this->PostModel->with(['cate','user'])->where($where)->order('id','desc')->paginate(10,false,['query' =>Request::instance()->param()]);

        $pagestr = $postlist->render();

        $this->assign([
            'count' => $count,
            'postlist' => $postlist,
            'pagestr' => $pagestr,
            'start' => $start,
            'end' => $end,
            'keywords' => $keywords
        ]);

        return $this->fetch();
    }

    public function del()
    {
        if($this->request->isPost()){

            $success = [
                'result' => false,
                'msg' => ''
            ];

            $id = $this->request->param('ids', 0);

            $postinfo = $this->PostModel->find($id);

            if(!$postinfo)
            {
                $this->error('帖子不存在');
                exit;
            }

            // 帖子表的软删除
            $result = $this->PostModel->destroy($id);

            // 前端传过来ID转换成数组
            $idarr = explode(',', $id);

            foreach ($idarr as $val){

                 // 查询该帖子下的所有评论
                $comment = $this->CommentModel->where(['postid' => $val])->select();

                // 评论ID
                $ids = [];

                foreach($comment as $item){
                    $ids[] = $item['id'];
                }

                // 评论表的软删除
                $res = $this->CommentModel->destroy($ids);
            }

            if($result === FALSE)
            {
                $success['result'] = false;
                $success['msg'] = $this->ConfigModel->getError();
            }else
            {
                $success['result'] = true;
                $success['msg'] = '删除帖子成功';
            }

            return $success;
        }


    }
}